package com.sevencar.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.example.lightble.BlueToothService;
import com.example.lightble.R;
import com.example.lightble.db.SettingDatabase;

import me.maxwin.view.XListView.IXListViewListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HomeFragment extends Fragment implements IXListViewListener {

	Activity mActivity = null;
	
	LinearLayout mDevLinearLayout = null;
	
	public static BlueToothService mBLEServiceInstance = null;  //采用第二种方式来做.
	public static List<LightDevItem> lstDevices = new ArrayList<LightDevItem>();  
	
	private   List<GroupItem> lstGroup = new ArrayList<GroupItem>();  
	
    
    private BluetoothAdapter mbluetoothAdapter ;
	ProgressDialog  mProgressDialog;
	
	
	
	public static final String ACTION_BLEDEV_NOT_EXIST = "com.example.bluetooth.le.ACTION_BLEDEV_NOT_EXIST";//设备不存在  
    public static final String ACTION_BLEGATT_NEED_NEW_PASSWORD ="com.example.bluetooth.le.ACTION_BLEGATT_NEED_NEW_PASSWORD"; //需要新的密码
    public static final String ACTION_BLEGATT_PASSWD_ERROR = "com.example.bluetooth.le.ACTION_BLEGATT_PASSWD_ERROR";    //反馈的命令.
    public static final String ACTION_BLEGATT_CONNECTED = "com.example.bluetooth.le.ACTION_BLEGATT_CONNECTED";    
    public static final String ACTION_BLEGATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_BLEGATT_DISCONNECTED";
    public static final String ACTION_BLEGATT_RECONNECT_FAILED = "com.example.bluetooth.le.ACTION_BLEGATT_DISCONNECTED";
    public static final String ACTION_BLEGATT_CONNECTING = "com.example.bluetooth.le.ACTION_BLEGATT_CONNECTING";
    
    private void listadd(List<LightDevItem> _lstDevices , LightDevItem item){
    	if(_lstDevices == null){
    		return;
    	}
    	int ii = 0;
    	for (int i = 0; i < _lstDevices.size(); i++) {
    		
    		System.out.println("1111111"+ _lstDevices.get(i).getDevAddress()+"----------------------"+item.getDevAddress());
			if(_lstDevices.get(i).getDevAddress().equals(item.getDevAddress())){
				ii = 1;
				return;
			}
		}
    	if(ii == 0){
    		_lstDevices.add(item);
    	}else {
			System.out.println("1111111111111111111111111111111111111111111");
		}
    }
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		

	    mActivity=getActivity();
	    if(mDevLinearLayout!=null){
		   mDevLinearLayout.removeAllViewsInLayout();
	    }
		View view = inflater.inflate(R.layout.fragment_home, container, false);
		mDevLinearLayout=(LinearLayout)view.findViewById(R.id.id_light_dev_linearlayout);
		
//		if(lstDevices.isEmpty()==false){
//			for(int i=0;i<lstDevices.size();i++)
//				mDevLinearLayout.addView(lstDevices.get(i));
//		}
		
		
		SettingDatabase dataBase= new SettingDatabase(mActivity, 0);
		
		
		List<Map<String, String>>  groupList=dataBase.query_maplist("select distinct group_code,group_name from table_group  ");

		Toast.makeText(mActivity, "----show create", 1000).show();
		 if(mDevLinearLayout!=null){
			 Toast.makeText(mActivity, "----sh---"+mDevLinearLayout.getChildCount(), 1000).show();
		 }
		 Toast.makeText(mActivity, "----show 0---"+lstDevices.size(), 1000).show();
//		Toast.makeText(mActivity, "----0---"+groupList.get(0).get("group_code"), 1000).show();
//		LinearLayout ll_group = (LinearLayout)view.findViewById(R.id.ll_group);
		
		lstGroup.clear();
		for (int i = 0; i < groupList.size(); i++) {
			GroupItem item=new GroupItem(getActivity(), groupList.get(i).get("group_code"),groupList.get(i).get("group_name").toString());
			mDevLinearLayout.addView(item);
			lstGroup.add(item);
			
			
		}
		
		
		
		//初始化 lstDevices
		List<Map<String, String>>  tempdeviceList=dataBase.query_maplist("select distinct device_address,device_name from table_temp_device  ");

		if(lstDevices.size()<=0){
			for (int i = 0; i < tempdeviceList.size(); i++) {
				listadd(lstDevices, new LightDevItem(getActivity(), tempdeviceList.get(i).get("device_address"),tempdeviceList.get(i).get("device_name")));
//				lstDevices.add(new LightDevItem(getActivity(), tempdeviceList.get(i).get("device_address"),tempdeviceList.get(i).get("device_name")));
			}
		}
		
		
		//初始化linearlayout
		for (int j = 0; j < lstDevices.size(); j++) {
			LightDevItem item=null;
			if(!checkDevice(lstDevices.get(j).getDevAddress())){
				
				System.out.println("listdevices size is " + lstDevices.size());
				for (int i = 0; i < mDevLinearLayout.getChildCount(); i++) {
					 
					if (mDevLinearLayout.getChildAt(i) instanceof LightDevItem) {
						
						LightDevItem tmpitem = (LightDevItem) mDevLinearLayout.getChildAt(i) ;
						if(tmpitem.getDevAddress().equals(lstDevices.get(j).getDevAddress())){
							item = tmpitem;
							break;
						}
					}
				}
				if(item==null) //
				{
					
						item= new LightDevItem(mActivity,lstDevices.get(j).getDevAddress(),lstDevices.get(j).getDevName());
					
					    
						mDevLinearLayout.addView(item);
						
//						lstDevices.add(item);
					
                }
				
			}
		}
		
		
		
		
		mActivity.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
		Log.i("sno","mActivity registerReceiver mGattUpdateReceiver ");
//		if(mBLEServiceInstance!=null){
//	    		mBLEServiceInstance.setScanLoop(true);
//	    		mBLEServiceInstance.startScanBle();  
//	    	ToastUtil.getToast(mActivity, "mBLEServiceInstance is not null").show();
//	    }else{
//	    	Log.i("sno","===============null ");
//	    	ToastUtil.getToast(mActivity, "mBLEServiceInstance is null").show();
//	    }
		
		
		
//		for (int i = 0; i < mDevLinearLayout.getChildCount(); i++) {
//			 
//			if (mDevLinearLayout.getChildAt(i) instanceof LightDevItem) {
//				
//				LightDevItem tmpitem = (LightDevItem) mDevLinearLayout.getChildAt(i) ;
//				if(checkDevice(tmpitem.getDevAddress())){
////					mDevLinearLayout.removeView(tmpitem);
//				}
//			}
//			
//			
//		}

		
		return view;
	}
	
	
	@Override
	public void onRefresh() {
		
	}

	@Override
	public void onLoadMore() {
		
	}
	
	public boolean checkDevice(String device){
		
		SettingDatabase sdb = new SettingDatabase(mActivity,0);
		
		List<Map<String, String>> hhhlist=sdb.query_maplist("select  * from table_group where device_address = '"+device+"'  ");
		sdb.close();
		return hhhlist.size()>0? true:false;
	}
	public boolean checktempDevice(String device){
		
		SettingDatabase sdb = new SettingDatabase(mActivity,0);
		
		List<Map<String, String>> hhhlist=sdb.query_maplist("select  * from table_temp_device where device_address = '"+device+"'  ");
		sdb.close();
		return hhhlist.size()>0? true:false;
	}
	
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) 
        {
        	if( mProgressDialog!=null){
        		 mProgressDialog.cancel();
        		 mProgressDialog=null;
        	}
            final String action = intent.getAction();
			if(BlueToothService.ACTION_BLESCAN_FIND_NEWDEVICE.equals(action)) //可能是新增,可能是设备连接好后主动断开,可能是界面操作断开后扫描到的.
			{
					BluetoothDevice device=(BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					if (device!=null && mDevLinearLayout!=null) 
					{
						LightDevItem item=null;
						if(!checkDevice(device.getAddress())){
							System.out.println("listdevices size is " + lstDevices.size());
							for (int i = 0; i < mDevLinearLayout.getChildCount(); i++) {
								if (mDevLinearLayout.getChildAt(i) instanceof LightDevItem) {
									LightDevItem tmpitem = (LightDevItem) mDevLinearLayout.getChildAt(i) ;
									if(tmpitem.getDevAddress().equals(device.getAddress())){
										item = tmpitem;
										break;
									}
								}
							}
							if(item==null) //新的设备. 
							{
								SettingDatabase sdb = new SettingDatabase(mActivity,0);
								
//								List<Map<String, String>> hhhlist=sdb.query_maplist("select  * from table_group where device_address = '"+device+"'  ");
								
								if(!checktempDevice(device.getAddress())){
									if(sdb.execSQL("insert into table_temp_device (device_address,device_name) values('"+device.getAddress()+"','"+device.getName()+"')")){
												
									}
								}
								item= new LightDevItem(mActivity,device);
								mDevLinearLayout.addView(item);
								listadd(lstDevices, item);
//								lstDevices.add(item);
								
								sdb.close();
								
									
								
			                }
							
//							for (LightDevItem option : lstDevices) {
//		                    	if(option.getDevAddress().equals(device.getAddress()))
//		                    	{
//		                    		item = option;
//		                    		break;
//		                    	}
//							}
//							if(item==null) //新的设备. 
//							{
//								
//									item= new LightDevItem(mActivity,device);
//									mDevLinearLayout.addView(item);
//									lstDevices.add(item);
//								
//			                }
						}else {
							System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
						}
						
						
						
					}
				}else if(ACTION_BLEDEV_NOT_EXIST.equals(action)) 
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null)
					 {
						 SettingDatabase sdb = new SettingDatabase(mActivity,0);
						 if(sdb.execSQL("delete from   table_temp_device where device_address ='"+tmpItem.getDevAddress()+"' ")){
							 lstDevices.remove(tmpItem);
						 }
						 sdb.close();
						
					 }
					 for (int i = 0; i < mDevLinearLayout.getChildCount(); i++) {
						 if(mDevLinearLayout.getChildAt(i).equals(tmpItem)){
							 mDevLinearLayout.removeView(tmpItem);
						 }
					}
				}
				else if(ACTION_BLEGATT_PASSWD_ERROR.equals(action)) 
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.showBondPasswdDialog("密码输入错误,请重新输入密码");
					 }
				}else if(ACTION_BLEGATT_NEED_NEW_PASSWORD.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.showBondPasswdDialog("请输入密码");
					 }
				}else if(ACTION_BLEGATT_CONNECTED.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 boolean isOpen=intent.getBooleanExtra("ISOPEN", false);
					 
//					 Toast.makeText(mActivity, "----actio1---"+ACTION_BLEGATT_CONNECTED, 1000).show();
					 
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
//						 Toast.makeText(mActivity, "tmpItem is not null -", 1000).show();
						 tmpItem.setConnected(isOpen);
					 }
				}else if(ACTION_BLEGATT_DISCONNECTED.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setDisconnect(false);
					 }
				}else if(ACTION_BLEGATT_CONNECTING.equals(action))
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setConnecting();
					 }
				}else if(ACTION_BLEGATT_RECONNECT_FAILED.equals(action))
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setReconnectFailed();
					 }
				}
		 }
      };
      private static IntentFilter makeGattUpdateIntentFilter() {
          final IntentFilter intentFilter = new IntentFilter();
          intentFilter.addAction(BlueToothService.ACTION_BLESCAN_FIND_NEWDEVICE);
          intentFilter.addAction(ACTION_BLEGATT_PASSWD_ERROR);
          intentFilter.addAction(ACTION_BLEDEV_NOT_EXIST);
          intentFilter.addAction(ACTION_BLEGATT_NEED_NEW_PASSWORD);
          intentFilter.addAction(ACTION_BLEGATT_CONNECTED);
          intentFilter.addAction(ACTION_BLEGATT_DISCONNECTED);
          intentFilter.addAction(ACTION_BLEGATT_CONNECTING);
          intentFilter.addAction(ACTION_BLEGATT_RECONNECT_FAILED);
          
          return intentFilter;
      }
      private LightDevItem getLightDevItem(BluetoothDevice dev,String hint){
     	 for(int i=0;i<lstDevices.size();i++){
 			  LightDevItem tmpItem=lstDevices.get(i);
 			  if(tmpItem == null){
 				  System.out.println("tmpitem is null");
 			  }
 			  if(dev == null){
 				  System.out.println("dev is null");
 			  }
 			  if(tmpItem.getDevAddress() == null){
 				  System.out.println("tmpItem.getDevAddress() is null");
 			  }
 			  
 			  if(dev!=null && tmpItem.getDevAddress().equals(dev.getAddress())){
 				  return tmpItem;
 			  }
 		  }
     	 Log.e("sno","getLightDevItem is ERROR---"+hint);
     	 return null;
      }
	

}
